package com.bankcomm.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.rytong.tools.utils.LPToastUtil;
import com.bankcomm.ui.BaseViewCopy;
import com.rytong.tools.utils.Utils;
import com.bankcomm.R;
/**
 * 自动下载更新
 * @author huang.x.h
 *
 * @date 2012-8-3 上午10:27:31
 */
public class DownloadThread {

	/** 相关变量 */
	public Thread runningThread = null;
	public ProgressDialog progressDownload = null;
	public boolean isStop = false;
	public ProgressBar progressBarDownload = null;
	private TextView progressTitle = null;
	static int ctrl = 0;
	
	// 是否第一次点下载按钮?
	public static boolean  IsFirst = true;
	
	// 交行apk的名字
	final String apkNameHead = "jtyh2g";
	String apkLpcName = "jtyh2g[0].apk";
	public String apkDownload;
	
	// 下载本地路径
	private final String localPath = "ebank_bocom";
	static boolean isReadOver = false;
	static boolean reload = false;
	
	// 是否重新下载
	boolean isGoDown = false;
	
	/** 状态列表 */
	private final static int MSG_CREATE_PROCESS = 0;
	private final static int MSG_SHOW_PROCESS = 1;
	private final static int MSG_DOWNLOAD_END = 2;
	private final static int MSG_SDCARD_UNAVIRABLE = 4;
	private final static int MSG_DOWNLOAD_FAILED = 5;
	private final static int MSG_USER_INTERRUPT = 6;
	
	
	/** 当前活动 */
	private BaseViewCopy baseView = null;
	
	/** 模拟器测试下载地址 */
//	private final String linkAddress = "http://182.119.173.65:8081/mobile/android/common/gphone_lingtu/lpc.apk";
//	private final String linkAddress = "http://182.119.117.224:9999/mobile/BankcommPad.apk";
	
	public DownloadThread(BaseViewCopy context) {
		baseView = context;
	}
	
	private Handler downLoadhandler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case MSG_CREATE_PROCESS:
					progressDownload = new ProgressDialog(baseView);
					progressDownload
							.setOnCancelListener(new OnCancelListener() {

								@Override
								public void onCancel(DialogInterface dialog) {
									isStop = true;
									progressDownload.dismiss();
									IsFirst = true;
								}
							});
					break;
				case MSG_SHOW_PROCESS:
					if (progressDownload != null
							&& !progressDownload.isShowing()) {
						progressDownload.show();
						// GeneralController.IsFirst = true;
						progressDownload
								.setContentView(R.layout.download_dialog_layout);
						progressBarDownload = null;
						progressTitle = null;
						progressBarDownload = (ProgressBar) progressDownload
								.findViewById(R.id.progressbar1);
						progressTitle = (TextView) progressDownload
								.findViewById(R.id.progress_title2);

						DisplayMetrics dm = new DisplayMetrics();
						baseView.getWindowManager().getDefaultDisplay()
								.getMetrics(dm);
						WindowManager.LayoutParams wmLp = progressDownload
								.getWindow().getAttributes();
						wmLp.width = dm.widthPixels - 20;
						progressDownload.getWindow().setAttributes(wmLp);
					}
					setProgressValue(ctrl);

					break;
				case MSG_DOWNLOAD_END:
					if (progressDownload != null
							&& progressDownload.isShowing()) {
						IsFirst = true;
						progressDownload.dismiss();
						isStop = true;
					}
					
					LPToastUtil.getInstance().getToast(msg.obj + " " + baseView.getResources().getString(R.string.download_over),baseView);
					break;
				case MSG_DOWNLOAD_FAILED:
					if (progressDownload != null
							&& progressDownload.isShowing()) {
						progressDownload.dismiss();
					}
					isStop = true;
					IsFirst = true;
					LPToastUtil.getInstance().getToast(baseView.getResources().getString(R.string.download_net_interrupt) + msg.obj,baseView);
					progressDownload = null;
					runningThread = null;
					String SDPath = Environment.getExternalStorageDirectory()
							+ File.separator + localPath + File.separator;
					File dir = new File(SDPath);
					if (!dir.exists())
						dir.mkdir();
					File file = new File(dir, apkLpcName);
					file.delete();
					reload = false;
					IsFirst = true;
					apkLpcName = "jtyh2g[0].apk";
					isGoDown = false;
					ctrl = 0;
					isReadOver = false;
					break;
				case MSG_SDCARD_UNAVIRABLE:
					if (progressDownload != null
							&& progressDownload.isShowing()) {
						progressDownload.dismiss();
						IsFirst = true;
					}
					isStop = true;
					LPToastUtil.getInstance().getToast(baseView.getResources().getString(R.string.download_no_sdcard),baseView);
					progressDownload = null;
					runningThread = null;
					break;
				case MSG_USER_INTERRUPT:
					if (progressDownload != null
							&& progressDownload.isShowing()) {
						IsFirst = true;
						progressDownload.dismiss();
					}
					LPToastUtil.getInstance().getToast(baseView.getResources().getString(R.string.download_user_interrupt),baseView);
					progressDownload = null;
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	
	
	public void downLoad() {
		if (null == runningThread) {
			startDownloadThread();
		} else {
			AlertDialog downDialog = null;
			Builder ad = new AlertDialog.Builder(baseView);
			final Resources res = baseView.getResources();
			if (isReadOver) {
				// 已经下载完了, 但尚未安装.
				ad.setTitle(res.getString(R.string.alert));
				ad.setMessage(res.getString(R.string.download_ask_install));
				ad.setPositiveButton(res.getString(R.string.download_install),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO
								// Auto-generated
								// method stub
								String SDPath = Environment
										.getExternalStorageDirectory()
										+ File.separator
										+ localPath
										+ File.separator;
								File f = new File(SDPath, apkLpcName);
								if (f.exists()) {
									installAPK(f);
								} else {
									LPToastUtil.getInstance().getToast(res.getString(R.string.download_file_not_exist),baseView);
									dialog.dismiss();
								}
							}

						});
				//
				ad.setNegativeButton(res.getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								IsFirst = true;
								dialog.dismiss();
							}

						});
				downDialog = ad.create();
				downDialog.show();
			} else {
				// 文件尚未下载完成, 继续下载?
				ad.setTitle(res.getString(R.string.alert));
				ad.setMessage(res.getString(R.string.download_ask_continue));
				ad.setPositiveButton(res.getString(R.string.download_continue),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								reload = false;
								isGoDown = true;
								startDownloadThread();
							}
						});
				ad.setNegativeButton(res.getString(R.string.download_again),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO
								// Auto-generated
								// method stub
								String SDPath = Environment
										.getExternalStorageDirectory()
										+ File.separator
										+ localPath
										+ File.separator;
								File dir = new File(SDPath);
								if (!dir.exists())
									dir.mkdir();
								File file = new File(dir, apkLpcName);
								file.delete();
								reload = false;
								isGoDown = false;
								// 删除本地文件
								startDownloadThread();
							}

						});
				IsFirst = true;
				downDialog = ad.create();
				downDialog.show();
			}
			
			// 设置下载框宽度
			/*if (downDialog != null) {
				Window alertWindow = downDialog.getWindow();
				WindowManager.LayoutParams wl = alertWindow.getAttributes();
				wl.alpha = 80;
				wl.width = Utils.screenWidth_ / 4;
				alertWindow.setAttributes(wl);
			}*/
		}
	}

	private void startDownloadThread() {
		runningThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				isStop = false;
				ctrl = 0;
				while (ctrl < 100 && !isStop) {
					if (null == progressDownload) {
						downLoadhandler.sendEmptyMessage(MSG_CREATE_PROCESS);
					} else {
						Utils.printOutToConsole("begin download file.");
						downloadFile();
					}
				}
				if (null != progressDownload && progressDownload.isShowing())
					progressDownload.dismiss();
			}

		});
		runningThread.start();
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public boolean isFileExist(String fileName, String path) {
		File file = new File(path + File.separator + fileName);
		return file.exists();
	}

	public void downloadFile() {
		// 将文件下载到SD卡
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			InputStream buffer = null;
			HttpURLConnection conn = null;
			FileOutputStream output = null;
			try {

				// 读取输入流
				URL url = new URL(apkDownload);
				conn = (HttpURLConnection) url.openConnection();
				// conn.setConnectTimeout(10000);
				// conn.setReadTimeout(20000);

				// 已下载内容大小
				long hasReadSize = 0;
				int fileSize = conn.getContentLength(); // 获取内容大小
				Utils.printOutToConsole("---------------------->fileSize"
						+ fileSize);

				if (fileSize > 0) {
					String SDPath = Environment.getExternalStorageDirectory()
							+ File.separator + localPath + File.separator;
					File dir = new File(SDPath);
					if (!dir.exists())
						dir.mkdir();
					if (!reload && !isGoDown) {
						int id = 0;
						boolean isexist = isFileExist(apkLpcName, SDPath);
						while (isexist) {
							id++;
							apkLpcName = apkNameHead + "[" + id + "].apk";
							isexist = isFileExist(apkLpcName, SDPath);
						}
					}

					File file = new File(dir, apkLpcName);
					if (file.exists()) {
						hasReadSize = file.length();
						if (hasReadSize > fileSize || reload) {
							file.delete();
							file.createNewFile();
							hasReadSize = 0;
						} else {
							ctrl = (int) (hasReadSize * 100 / fileSize);
						}
					} else {
						file.createNewFile();
					}
					downLoadhandler.sendEmptyMessage(MSG_SHOW_PROCESS);

					// 设置断点续传的开始位置
					// conn.setRequestProperty("Connection", "Keep-Alive");
					// conn.setRequestProperty("RANGE", "bytes=" + hasReadSize);

					if (conn.getResponseCode() == 200) {
						buffer = conn.getInputStream();

						// 写入文件(附加方式 )
						output = new FileOutputStream(file, true);
						byte[] buf = new byte[1024];
						int readNum = 0;
						Utils.printOutToConsole("skip size: " + hasReadSize);

						// 断点续传
						long actualSkip = buffer.skip(hasReadSize);
						while (actualSkip < hasReadSize) {
							Utils.printOutToConsole("actual skip num: "
									+ actualSkip);
							long tempSkip = buffer.skip(hasReadSize
									- actualSkip);
							actualSkip += tempSkip;
							Utils.printOutToConsole("temp skip num: "
									+ tempSkip + "\n");
						}

						while (!isStop && (readNum = buffer.read(buf)) != -1) {
							output.write(buf, 0, readNum);
							hasReadSize += readNum;
							ctrl = (int) (hasReadSize * 100 / fileSize);
							downLoadhandler.sendEmptyMessage(MSG_SHOW_PROCESS);
						}
						if (ctrl == 100 && hasReadSize == fileSize) {
							isReadOver = true; // 表明已经读完了
						}
						if (!isStop) {
							output.flush();
							Message message = new Message();
							message.what = MSG_DOWNLOAD_END;
							message.obj = SDPath + apkLpcName;
							downLoadhandler.sendMessage(message);

							// 安装文件
							installAPK(file);
						} else {
							sendInterupt();
						}
					}
				} else {
					sendFail(baseView.getResources().getString(R.string.download_no_content));
				}
			} catch (Exception e) {
				e.printStackTrace();
				sendFail(e.toString());
			} finally {
				try {
					if (null != conn)
						conn.disconnect();
					if (buffer != null)
						buffer.close();
					if (output != null)
						output.close();
				} catch (IOException e1) {
					// e1.printStackTrace();
				}
			}
		} else {
			// SD卡未插上.
			sendNoSD();
		}
	}

	private void installAPK(File f) {
		reload = false;
		IsFirst = true;
		// runningThread = null;
		apkLpcName = apkNameHead + "[0].apk";
		if (ctrl == 100) {
			ctrl = 0;
		}

		// isReadOver = false;
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(f),
				"application/vnd.android.package-archive");
		// LPUtils.exitSystem(lplView);
		baseView.startActivity(intent);
	}

	public void sendInterupt() {
		Message message = new Message();
		message.what = MSG_USER_INTERRUPT;
		downLoadhandler.sendMessage(message);
	}

	public void sendFail(String str) {
		Message message = new Message();
		message.what = MSG_DOWNLOAD_FAILED;
		message.obj = str;
		downLoadhandler.sendMessage(message);
	}

	public void sendNoSD() {
		Message message = new Message();
		message.what = MSG_SDCARD_UNAVIRABLE;
		downLoadhandler.sendMessage(message);
	}

	private void setProgressValue(int pos) {
		// 设置进度值显示和进度条的值
		progressBarDownload.setProgress(pos);

		progressTitle.setText("" + pos + "%");
	}
	// end

	public void setApkDownload(String apkDownload) {
		this.apkDownload = apkDownload;
	}
}
